package com.thlws.java.jdk8.function;

import com.thlws.java.jdk8.function.entity.Result;
import com.thlws.java.jdk8.function.entity.User;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 函数式接口：只有一个方法的接口(Object同名的method不算在内,比如接口包含equals方法).
 * lambda:
 *      其实就函数式接口的实现，与普通内部类不同的是，lambda是一个简写形式,可读性很高.
 *      表达式中的this指的不是 lambda 语句块，它实际是声明该表达式的对象,该示例指的就是Demo对象
 *      表达式可以强制类型转换，Object o = (Runnable) () -> { System.out.println("hi"); };
 *
 *
 * @author HanleyTang
 * @date 2018/11/21
 */
public class FunctionDemo {

    public static void main(String[] args) {
        FunctionDemo demo = new FunctionDemo();
//        demo.testPredicate();
//         demo.testConsumer();
        demo.testFunction();

    }


    //用于传值判断
    public  void testPredicate(){

        //内部接口实现
        Predicate<Long> varNum = new Predicate<Long>() {
            @Override
            public boolean test(Long val) {
                //处理判断逻辑
                return val > 10;
            }
        };

        //lambda表达式实现,功能同上
        Predicate<Long> varNum2 = (val) ->{
            return val < 20;
        };


        boolean flag1 = varNum2.test(11L);
        boolean flag2 = varNum2.test(6L);
        System.out.println("flag1="+flag1+",flag2="+flag2);

        //多条件使用
        boolean flag3 = varNum2.and(varNum).test(19L);
        boolean flag4 =varNum2.and(varNum).test(21L);
        System.out.println("flag3="+flag3+",flag4="+flag4);
    }


    //修改被传递的值,无返回值,直接修改传入的值
    public  void testConsumer(){

        User u = new User("hanley", "123456");

        //内部接口实现
        Consumer<User> consumer = new Consumer<User>() {
            @Override
            public void accept(User user) {
                user.setPassWord("111111");
            }
        };

        consumer.accept(u);
        System.out.println("consumer->"+u.getPassWord());

        //lambda表达式实现,功能同上
        Consumer<User> consumer2 = user -> user.setPassWord("222222");
        consumer2.accept(u);
        System.out.println("consumer2->"+u.getPassWord());
    }


    //修改被传递的值，并且返回一个对象
    public  void testFunction(){

        User u = new User("hanley", "123456");

        Function<User, Result> function = user -> {

            boolean flag = user.getUserName().equals("hanley") && user.getPassWord().equals("123456");
            Result result = new Result();
            System.out.println("this means = " + this.getClass().getName());
            if (flag){
                result.setDesc("验证正常");
                result.setOk(true);
            }else {
                result.setDesc("验证失败");
                result.setOk(false);
            }
            return result;
        };

       Result result = function.apply(u);
        System.out.println("result="+result);
    }

}
